package tools.model {
	import kiwi.util.GeomUtils;
	import kiwi.util.sprintf;

	import flash.display.BitmapData;
	import flash.geom.Point;

	/**
	 * @author zhangming.luo
	 */
	public class FrameInfo {
		public var id : int;
		public var name : String;
		public var tileList : Array = [];
		public var $source : TextureBitmap;
		public var $width : int;
		public var $height : int;
		public var $registration : Point;

		public function drawBitmap(canvas : BitmapData, destPosition : Point) : void {
			canvas.lock();
			var tmp : Point = GeomUtils.TMP_POINT;
			var sourceBD : BitmapData = $source.bitmapData;
			for each (var tile:TileInfo in tileList) {
				tmp.x = destPosition.x - tile.registration.x;
				tmp.y = destPosition.y - tile.registration.y;
				canvas.copyPixels(sourceBD, tile.source, tmp);
			}
			canvas.unlock();
		}

		public function getBitmapData() : BitmapData {
			updateSize();
			var tmp : Point = GeomUtils.TMP_POINT;
			var canvas : BitmapData = new BitmapData($width, $height, true, 0x0);
			for each (var tile:TileInfo in tileList) {
				tmp.x = $registration.x - tile.registration.x;
				tmp.y = $registration.y - tile.registration.y;
				canvas.copyPixels(tile.$source.bitmapData, tile.source, tmp, null, null, true);
			}
			return canvas;
		}

		private function updateSize() : void {
			if ($width && $height) {
				return;
			}
			var left : int = 0;
			var right : int = 0;
			var top : int = 0;
			var bottom : int = 0;
			for each (var tile:TileInfo in tileList) {
				left = Math.min(left, -tile.registration.x);
				right = Math.max(right, tile.source.width - tile.registration.x);
				top = Math.min(top, -tile.registration.y);
				bottom = Math.max(bottom, tile.source.height - tile.registration.y);
			}
			$width = right - left;
			$height = bottom - top;
			$registration = new Point(-left, -top);
		}

		public static function fromTile(tile : TileInfo, id : int = 0, name : String = null) : FrameInfo {
			var info : FrameInfo = new FrameInfo();
			info.id = id ? id : tile.id;
			info.tileList = [tile];
			info.name = name ? name : tile.name;
			return info;
		}

		public function toString() : String {
			return sprintf("%3d: %s", id, name);
		}
	}
}
